package stpmproject.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * encoding: utf-8
 *
 * @Author: kou dui
 * @Date: 2019/4/25 19:39
 * @software: IntelliJ IDEA
 * @file: ValidatorImpl
 * @description:
 */
@Component
public class ValidatorImpl implements InitializingBean {
    //创建一个javax的Validation对象用于处理验证
    private Validator validator;
    @Override
    public void afterPropertiesSet() throws Exception {
        //通过Validation的默认工厂构造方法创建一个validator对象
        this.validator= Validation.buildDefaultValidatorFactory().getValidator();
    }
    public ValidatorResult validate(Object bean){
        ValidatorResult result=new ValidatorResult();
        Set<ConstraintViolation<Object>> constraintValidatorSet=validator.validate(bean);
        if(constraintValidatorSet.size()>0){
            result.setHasErr(true);
            constraintValidatorSet.forEach(constraint ->{
                String errMsg=constraint.getMessage();
                String propertyName=constraint.getPropertyPath().toString();
                result.getErrMap().put(propertyName,errMsg);
            });
        }
        return result;
    }
}
